package xyz.molzhao.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加密工具
 */
@Slf4j
public class DataDesensitizationUtils {
    private DataDesensitizationUtils() {

    }

    private static final String KEY = "8ce87b8aa3463f4561635f66991592ae";
    /**
     * 加密
     * @param data
     * @return
     * @throws Exception
     */
    public static String encrypt(String data) {
        try {
            byte[] plaintext = data.getBytes();
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(KEY.substring(0, 16).getBytes(), "AES"), new IvParameterSpec(KEY.substring(16).getBytes()));
            byte[] encrypted = cipher.doFinal(plaintext);
            return new BASE64Encoder().encode(encrypted).trim();
        } catch (Exception e) {
            log.error("加密数据失败", e);
            return null;
        }
    }

    /**
     * 解密
     * @param data
     * @return
     */
    public static String decrypt(String data) {
        try {
            byte[] encrypted = new BASE64Decoder().decodeBuffer(data);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.substring(0, 16).getBytes(), "AES"), new IvParameterSpec(KEY.substring(16).getBytes()));
            byte[] original = cipher.doFinal(encrypted);
            String originalString = new String(original);
            return originalString.trim();
        } catch (Exception e) {
            log.error("解密数据失败", e);
            return null;
        }
    }
}
